/**
 * Created by ziyu on 17/5/8.
 */

import React, {Component, PropTypes} from 'react'
import Styles from './Index.less'
import SearchStyle from '../../common/less/search.less'
import {message, Col, Icon, Button,Statistic, Modal, Form, Input, Spin} from 'antd'
import {fetchPost} from '../../../utils/request'
import List from './List'
import Pannel from '../../common/components/Pannel'
import Search from '../../common/components/Search'
import DlButton from '../../common/components/download/DlButton'
import Detail from './details/Index'
import moment from 'moment'

const FormItem = Form.Item

class Index extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            loading: false,
            isNBFCAdmin: false,
            isAgentManager: false,
            collectionType: props.collectionType,
            conclusion: props.conclusion,
            api: props.api,
            id: null,
            userId: null,
            tradeNo: null,
            activeKey: 'baseInfo',
            item: {},
            page: {
                currentPage: 1,
                pageSize: 20,
                totalCount: 0
            },
            outCallParams: {
                fromExten: '',
                exten: '',
            },
            switchBoolean: true,
            params: {
                findType: '',
                collectionStatus: '',
                overdueTime: '',
                overdueDays: '',
                inputValue: '',
                overdueType: '',
                activeType: null,
                sort: '1',
                sortType: 'lastCall',
                workTaskStatus: 'doing',
                startDate: moment().format('YYYY-MM-DD'),
                endDate: moment().format('YYYY-MM-DD'),
            },
            panelParams: [],
            searchParams: {
                list: [
                    {
                        name: 'Paid status',
                        type: 'select',
                        key: 'workTaskStatus', //催收状态 doing、completed、transferred
                        className: 'pr20',
                        values: [
                            {value: 'doing', name: 'Unpaid'},
                            {value: 'completed', name: 'Paid'},
                            {value: 'transferred', name: 'Transferred'},
                        ],
                        defaultValue: 'doing',
                    },
                    {
                        name: 'Loan ID',
                        type: 'text',
                        key: 'tradeNo',
                        className: 'pr20',
                        placeHolder: 'Please enter the loan ID',
                        values: []
                    },
                    {
                        name: 'Mobile',
                        type: 'text',
                        key: 'mobile',
                        className: 'pr20',
                        placeHolder: 'Please enter the mobile',
                        values: []
                    },
                    {
                        name: 'Status',
                        type: 'select',
                        key: 'collectionStatus',
                        className: 'pr20',
                        values: [{value: '', name: 'Please Select'}]
                    },
                    {
                        name: 'Days Overdue',
                        type: 'text',
                        key: 'overdueDays',
                        className: 'pr20',
                        placeHolder: 'Please enter a day',
                        values: []
                    },
                    {
                        name: '',
                        type: 'search',
                        key: '',
                        className: 'pr20',
                        values: []
                    }
                ],
                api: '/collection/v2/case/query'
            },
            list: [],
            countInfo: {},
            isShowPanel: false,
            visible: false,
            phoneStatus: 0,
            operateAllow: true,
        }
    }

    componentDidMount() {
        this.getData()
        this.getStatus()
        this.getCollectionAgentConfig()
    }

    componentWillReceiveProps(props) {
        if (props.collectionType != this.state.collectionType
            || props.conclusion != this.state.conclusion) {
            this.setState({
                collectionType: props.collectionType,
                conclusion: props.conclusion,
                api: props.api,
            }, () => {
                this.getData()
            })
        }
    }

    getStatus() {
        let self = this
        fetchPost('/collection/v2/addressBook/status/get').then(res => {
            if (res.code === 0) {
                // debugger;
                self.setState({
                    phoneStatus: res.data.status
                })
            }
        })
    }

    getCollectionAgentConfig() {
        let self = this
        fetchPost('/collection/v2/agent/config').then(res => {
            if (res.code === 0) {
                self.setState({
                    isAgentManager: res.data.isAgentManager
                })
            }
        })
    }

    getData() {
        let copyState = {}
        let self = this
        this.setState({
            loading: true
        })
        for (let i in this.state.params) {
            if (this.state.params[i] !== '') {
                copyState[i] = this.state.params[i]
            }
        }

        function GetList() {
            return new Promise((resolve, reject) => {
                fetchPost(
                    `${self.state.api}?currentPage=${self.state.page.currentPage}&pageSize=${self.state.page.pageSize}`,
                    {
                        ...copyState,
                        collectionType: self.state.collectionType,
                        conclusion: self.state.conclusion
                    }).then(res => {
                    if (res.code === 0) {
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        }

        Promise.all([GetList()]).then(res => {
            let [listData, index] = [res[0], 0]
            if (listData.code === 0) {
                let list = listData.data.itemList
                if (list.length) {
                    if (this.state.id) {
                        for (let i in listData.data.itemList) {
                            if (listData.data.itemList[i].orderId == this.state.id) {
                                index = i
                            }
                        }
                    }

                    this.setState({
                        id: list[index].collectionNo,
                        userId: list[index].tradeNo,
                        tradeNo: list[index].tradeNo,
                        loading: false,
                        page: {
                            ...this.state.page,
                            totalCount: listData.page.totalCount || 0
                        },
                        item: list[index],
                        activeKey: 'baseInfo',
                        isFetch: true,
                        list: list,
                        countInfo: listData.data.countInfo,
                    }, () => {
                    })
                } else {
                    self.setState({
                        id: null,
                        userId: null,
                        tradeNo: null,
                        loading: false,
                        orderStatus: null,
                        item: {},
                        activeKey: 'baseInfo',
                        isFetch: true,
                        list: [],
                        countInfo: listData.data.countInfo,
                        page: {
                            ...this.state.page,
                            totalCount: listData.page.totalCount || 0
                        },
                    })
                    message.warning('There\'s No data')
                }
            } else {
                self.setState({
                    id: null,
                    userId: null,
                    tradeNo: null,
                    loading: false,
                    orderStatus: null,
                    item: {},
                    activeKey: 'baseInfo',
                    isFetch: true,
                    list: [],
                    countInfo: {},
                    page: {
                        ...this.state.page,
                        totalCount: 0
                    },
                }, () => {
                    message.error(listData.msg)
                })
            }

        }, (error) => {
            self.setState({
                id: null,
                userId: null,
                tradeNo: null,
                orderStatus: null,
                loading: false,
                item: {},
                activeKey: 'baseInfo',
                isFetch: true,
                list: [],
                countInfo: {},
            }, () => {
                message.error(error.msg)
            })
        })
    }

    currentPage(current) {
        this.setState({
            page: {
                ...this.state.page,
                currentPage: current
            }
        }, () => {
            this.getData()
        })
    }

    chooseOrder(data) {
        this.setState({
            ...data
        })
    }

    changeParams(params) {
        let newParams = this.state.params
        console.info('11111111:' + JSON.stringify(newParams))
        Object.assign(newParams, params)
        console.info('22222222:' + JSON.stringify(newParams))

        if (newParams.workTaskStatus && newParams.workTaskStatus === 'doing') {
            this.setState({
                operateAllow: true
            })
        } else {
            this.setState({
                operateAllow: false
            })
        }

        if (params.inputValue || params.findType) {
            if (params.findType && params.inputValue) {
                this.setState({
                    params: newParams,
                    isFetch: false
                }, () => {
                    this.getData()
                })
            } else {
                message.warning('Please choose the Filter and enter the value')
            }
        } else {
            this.setState({
                params: newParams,
                isFetch: false
            }, () => {
                this.getData()
            })
        }
    }

    handleCallCenter() {
        this.props.form.validateFields((error, values) => {
            if (!error) {
                const {fromExten} = values
                this.setState({
                    visible: false,
                    outCallParams: {
                        ...this.state.outCallParams,
                        fromExten,
                    }
                }, () => {
                    console.log('--jobNumber--', this.state.outCallParams)
                    this.props.form.resetFields()
                })
            }
        })
    }

    outCallDo(phone) {
        const self = this
        const {fromExten} = this.state.outCallParams
        const _params = {
            fromExten,
            exten: phone,
        }
        if (fromExten.length) {
            fetchPost(`/collection/outer/call`, _params).then(res => {
                if (res.code === 0) {
                    message.info(res.msg)
                    self.setState({
                        outCallParams: {
                            ...this.state.outCallParams,
                            ..._params,
                        }
                    })
                } else {
                    message.error(res.msg)
                }
            })
        } else {
            message.info('Please enter the agent number first!')
        }
    }

    refreshList() {
        this.getData()
    }

    switchChange() {
        const {switchBoolean, params} = this.state
        let sort = ''
        if (switchBoolean) {
            sort = '2'
        } else {
            sort = '1'
        }
        this.setState({
            switchBoolean: !switchBoolean,
            params: {
                ...params,
                sort,
            }
        }, () => {
            this.getData()
        })
    }

    render() {
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 14},
        }
        const {getFieldDecorator} = this.props.form

        return (
            <div className={Styles.box}>
                <Modal title="Agent number" visible={this.state.visible} onOk={() => {
                    this.handleCallCenter()
                }} onCancel={() => {
                    this.setState({
                        visible: false,
                    })
                }}>
                    <Form horizontal>
                        <FormItem
                            {...formItemLayout}
                            label="Agent number"
                        >
                            {getFieldDecorator('fromExten', {
                                rules: [
                                    {required: true, message: 'Agent number can not be empty'},
                                    // {pattern: /^80[0-9]*$/, message: '请输入正确的坐席工号'},
                                    {whitespace: true}
                                ]
                            })(
                                <Input placeholder='Please enter the agent number'/>
                            )}
                        </FormItem>
                    </Form>
                </Modal>
                <div className={SearchStyle.searchClass}>
                    <div style={{width: "10%", float: "left"}}>
                        
                    </div>
                    <div style={{width: "80%", float: "left"}}>
                        <Search searchParams={this.state.searchParams}
                                changeParams={(params) => this.changeParams(params)} callPutButton={() => {
                            this.setState({
                                visible: true
                            })
                        }}/>
                    </div>
                </div>

                <div>
                    {/*<DlButton downloadParams={this.state.params} downloadUrl='/collection/v2/distributeOrderGet/list/export'/>*/}
                </div>

                {
                    this.state.isShowPanel ? <div className='mt20'>
                            <Pannel panelParams={this.state.panelParams}/>
                        </div>
                        : ''
                }
                <Spin spinning={this.state.loading} delay={200}>
                    <div className={Styles.detailWrapper}>
                        <Col span={12}>
                            <div className={Styles.listClass}>
                                <div>
                                    <List
                                        list={this.state.list}
                                        countInfo={this.state.countInfo}
                                        id={this.state.id}
                                        userId={this.state.userId}
                                        isFetch={this.state.isFetch}
                                        page={this.state.page}
                                        chooseOrder={(params) => this.chooseOrder(params)}
                                        currentPage={(current) => this.currentPage(current)}
                                        switchChange={() => this.switchChange()}
                                    />
                                </div>
                            </div>
                        </Col>

                        <Col span={12}>
                            <div id='detailClass' className={Styles.detailClass}>
                                <Detail
                                    activeKey={this.state.activeKey}
                                    id={this.state.id}
                                    userId={this.state.userId}
                                    item={this.state.item}
                                    refreshList={() => {
                                        this.refreshList()
                                    }}
                                    changeOrder={(type, id) => this.changeOrder(type, id)}
                                    collectionType={this.state.collectionType}
                                    outCallDo={(phone) => this.outCallDo(phone)}
                                    phoneStatus={this.state.phoneStatus}
                                    isNBFCAdmin={this.state.isNBFCAdmin}
                                    operateAllow={this.state.operateAllow}
                                    isAgentManager={this.state.isAgentManager}
                                />
                            </div>
                        </Col>

                    </div>
                </Spin>

            </div>
        )
    }
}

Index = Form.create()(Index)
export default Index
